const MOUSE_POS_LIST = document.querySelector('#MOUSE_POS_LIST');
const REFRESH = document.querySelector('#REFRESH');

const drawTable = rows => {
    MOUSE_POS_LIST.textContent = '';
    let tr = document.createElement("tr");
    tr.innerHTML = `
        <th>序号</th>
        <th>时间</th>
        <th>注记</th>
        <th>操作</th>
    `
    MOUSE_POS_LIST.appendChild(tr);

    for (let i = 0; i < rows.length; i++) {
        tr = document.createElement("tr");
        tr.innerHTML = `
        <td>${i + 1}</td>
        <td>${formatDate((new Date(rows[i].c_time)))}</td>
        <td>${rows[i].note }</td>
        <td>
            <button class="click_btn" onclick="click_pos(${rows[i].id})" >测试</button>
            <button class="click_btn" onclick="del_pos(${rows[i].id})" >删除</button>
            <button class="click_btn" onclick="alt_note(this)" note="${rows[i].note}" posid="${rows[i].id}" >备注</button>
        </td>`;
        MOUSE_POS_LIST.appendChild(tr);
    }
};

const listTable = () => {
    getJson('/action/mouse/all', rows => {
        console.log('all Table, length:', rows.length);

        drawTable(rows);
    });
}

listTable();

REFRESH.addEventListener('click', () => {
    listTable();
});

const click_pos = id => {
    console.log('click pos', id);
    fetch(`/action/mouse/clicks/${id}`);
}

const del_pos = id => {
    console.log('delete pos', id)
    delAsk(`/action/mouse/pos/${id}`, () => {
        listTable();
    })
}

const alt_note = function (btn) {
    let note = btn.getAttribute('note') || '';
    note = window.prompt('修改注记', note);
    let id = Number.parseInt(btn.getAttribute('posid'));
    if (isNaN(id) || id <= 0) return alert('系统出错');
    patchData(`/action/mouse/pos/${id}`, { note },()=>{
        listTable();
    });
}